import { ref, onUnmounted } from 'vue';

// UDP 服务类
class UdpService {
    constructor() {
        this.isListening = ref(false);
        // 移除大量数据存储，只保留状态标识
    }

    // 开始监听 UDP
    async startListening(address, port,selectedTaskId, allParam,confirmedSelectedParam,telemetryDataSaveFileFolder) {
        try {
            // 序列化复杂对象以避免Electron IPC的序列化问题
            const serializedAllParams = JSON.stringify(allParam);
            const serializedSelectedParams = JSON.stringify(confirmedSelectedParam);
            const result = await window.electronAPI.startUdpListener(address, port,selectedTaskId, serializedAllParams,serializedSelectedParams,telemetryDataSaveFileFolder);
            console.log(result);
            if (result.success) {
                this.isListening.value = true;
                return result;
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            console.error('Failed to start UDP listener:', error);
            throw error;
        }
    }

    // 停止监听 UDP
    async stopListening() {
        try {
            const result = await window.electronAPI.stopUdpListener();
            if (result.success) {
                this.isListening.value = false;
                return result;
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            console.error('Failed to stop UDP listener:', error);
            throw error;
        }
    }

    // 监听 UDP 数据
    onData(callback) {
        console.log('UDP data listener registered');
        window.electronAPI.onUdpData((event, data) => {
            // 打印详细日志以便调试
            console.log('Received UDP data from main process:', data);
            console.log('UDP data length:', data?.data?.length || 0);
            if (callback) {
                console.log('Calling UDP data callback');
                callback(data);
            }
        });
    }

    // 清理监听器
    cleanup() {
        window.electronAPI.removeAllListeners('udp-data');
    }
}

// Vue 组合式函数
export function useUdp() {
    const udpService = new UdpService();

    onUnmounted(() => {
        udpService.cleanup();
    });

    return {
        isListening: udpService.isListening,
        startListening: udpService.startListening.bind(udpService),
        stopListening: udpService.stopListening.bind(udpService),
        onData: udpService.onData.bind(udpService),
        cleanup: udpService.cleanup.bind(udpService)  // 新增：导出cleanup方法
    };
}

export default UdpService;
